<template>
  <div style="position:relative">
    <input type="radio" :value="0" v-model="maptype" @change="initMap()" />世界
    <input type="radio" :value="1" v-model="maptype" @change="initMap()" />中国
    <div class="toparea">
      <div class="mapitem" v-for="(map, index) in mapArea" :key="map.name">
        <span @click="tabMap(map, index)">{{ map.name }}</span>
        <i v-if="showIcons(index)">></i>
      </div>
    </div>
    <div class="box" ref="box1"></div>
    <div class="echart-card" :style="waperStyle">
      <div>
        <div class="flex set" v-for="(item, index) in filterKehu" :key="index" @click="gotBoard(item)">
          <img src="@/assets/map/weizhi.png" />
          <div class="qiyename">{{ item.name }}</div>
          <div class="" v-if="isEdit">
            <img src="@/assets/map/shezhi.png" style="cursor:pointer;" width="25px" alt="">
          </div>
          <div v-else>
            <img v-if="item.url" style="cursor:pointer;" src="@/assets/map/jiantou.png" width="25px" alt="">
            <img v-else src="@/assets/map/jinzhi.png" width="25px" alt="" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios"
import * as echarts from 'echarts';
import china from "../assets/json/100000.json"
import world from "../assets/json/world.json"

export default {
  name: "Map",
  props: {
    isEdit: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      // 0-世界、1-国家、2-省份、3-市区、4-区
      maptype: 1,
      chart: undefined,
      mapArea: [],
      defaultData: [
        {
          "name": "护理佳",
          "address": "中国-上海市-青浦区",
          "11824": 1,
          "11825": 1,
          "11826": 1,
          "id": "1639642874000000000"
        },
        {
          "name": "客户A",
          "address": "中国-上海市-奉贤区",
          "11824": 2,
          "11825": 2,
          "11826": 3,
          "id": "1639642875000000000"
        },
        {
          "name": "客户B",
          "address": "中国-北京市-丰台区",
          "11824": 2,
          "11825": 3,
          "11826": 5,
          "id": "1639642876000000000"
        },
        {
          "name": "客户C",
          "address": "中国-北京市-东城区",
          "11824": 1,
          "11825": 4,
          "11826": 6,
          "id": "1639643029000000000"
        },
        {
          "name": "客户D",
          "address": "中国-北京市-石景山区",
          "11824": 1,
          "11825": 5,
          "11826": 7,
          "id": "1639643030000000000"
        },
        {
          "name": "客户E",
          "address": "中国-云南省-玉溪市-江川区",
          "11824": 1,
          "11825": 6,
          "11826": 8,
          "id": "1639643031000000000"
        },
        {
          "name": "客户F",
          "address": "中国-广西壮族自治区-桂林市-叠彩区",
          "11824": 1,
          "11825": 7,
          "11826": 9,
          "id": "1639643034000000000"
        },
        {
          "name": "客户G",
          "address": "中国-天津市-河西区",
          "11824": 3,
          "11825": 3,
          "11826": 4,
          "id": "1640242087000000000"
        },
        {
          "name": "额外企鹅委屈",
          "address": "中国-重庆市-大渡口区",
          "id": "1640331845000000000"
        },
        {
          "name": "额外企鹅委屈",
          "address": "中国-天津市-河西区",
          "id": "1640331901000000000"
        },
        {
          "name": "234234",
          "address": "德国",
          "id": "1663828863000000000"
        },
        {
          "name": "zcxvasdf",
          "address": "中国-江苏省",
          "id": "1663828875000000000"
        },
        {
          "name": "老爹最伟大",
          "address": "中国-河南省-洛阳市-西工区",
          "11824": 99,
          "id": "1663828891000000000"
        },
        {
          "name": "滴答答",
          "address": "中国-河南省-郑州市-金水区",
          "11824": 99,
          "id": "1663828891000000000"
        },
        {
          "name": "测试1",
          "address": "中国-河南省-洛阳市-洛龙区",
          "11824": 22,
          "id": "1663839042000000000"
        }
      ],
      waperStyle: {},
      kehudata: [],
      urldataArray: {
        "测试1": "http://www.baidu.com",
        "客户E": "https://www.yuque.com/",
      }
    }
  },
  computed: {
    // 绑定的跳转url赋值
    filterKehu() {
      var data = [];
      this.kehudata.forEach(e => {
        var url = this.urldataArray[e];
        data.push({ name: e, url: url })
      })

      return data;
    }
  },
  mounted() {
    var constat = this.$refs.box1;
    this.chart = echarts.init(constat);

    this.initMap();

    var self = this;
    this.chart.on('mousemove', function (params) {
      self.waperStyle = {
        display: 'none',
      };
    });

    this.chart.on('click', function (params) {
      // console.log(params)
      if (params.componentSubType == "effectScatter") {
        // 赋值客户信息
        self.kehudata = params.data.data;

        self.waperStyle = {
          display: 'block',
          top: params.event.offsetY + "px",
          left: params.event.offsetX + "px"
        };
      } else {
        self.waperStyle = {
          display: 'none',
        };

        var name = params.name;
        var geodata = null;

        // 层级叠加
        self.maptype++;

        // TODO:直辖市特殊处理
        if (self.maptype == 3 && (params.data.code.toString().indexOf("310") == 0)) {
          jsonUrl = `https://geo.datav.aliyun.com/areas_v3/bound/${params.data.code}.json`;
        } else if (self.maptype == 4) {
          jsonUrl = `https://geo.datav.aliyun.com/areas_v3/bound/${params.data.code}.json`;
        } else {
          var jsonUrl = `https://geo.datav.aliyun.com/areas_v3/bound/${params.data.code}_full.json`;
        }

        axios.get(jsonUrl).then(res => {
          // console.log(res)
          geodata = res.data;

          // 通过对应json文件获取 子对象坐标和编码
          // 到区一级就没有向下坐标了
          var mapInfoArray = {};
          for (var i = 0; i < geodata.features.length; i++) {
            mapInfoArray[geodata.features[i].properties.name] = [geodata.features[i].properties.adcode, geodata.features[i].properties.center];
          }
          // console.log(geodata);
          // 获取展示的数据信息
          if (self.maptype == 4) {
            // 县区也仅显示到县区信息
            var data = self.getLayerData(self.maptype - 1, name, mapInfoArray);
          } else {
            if (self.maptype == 3 && (params.data.code.toString().indexOf('310') == 0)) {
              var data = self.getLayerData(self.maptype - 1, name, mapInfoArray);
            } else {
              var data = self.getLayerData(self.maptype, name, mapInfoArray);
            }
          }

          // 渲染地图
          self.loadMap(geodata, name, data, mapInfoArray);

          // 创建顶部路径
          self.mapArea.push({ name: name, codeData: geodata, data: data, geoCoordMap: mapInfoArray, index: self.maptype });
        })
      }
    });
  },
  methods: {
    initMap() {
      this.chart.showLoading();
      this.mapArea = [];

      if (this.maptype == 0) {
        echarts.registerMap('world', world);

        // 世界地图相关暂时只用中国
        var geoCoordMap = { '中国': [100000, [109.44362810937501, 32.20520670312501]] };
        var dataArray = this.getLayerData(0, '', geoCoordMap);

        this.mapArea.push({ name: "世界", codeData: world, data: dataArray, geoCoordMap, index: 0 });
        this.loadMap(world, 'world', dataArray, geoCoordMap);

      } else if (this.maptype == 1) {
        echarts.registerMap('china', china);

        // 获取地图上所有的中心坐标和code
        var mapInfoArray = {};
        for (var i = 0; i < china.features.length; i++) {
          mapInfoArray[china.features[i].properties.name] = [china.features[i].properties.adcode, china.features[i].properties.center];
        }

        var dataArray = this.getLayerData(1, '中国', mapInfoArray);
        this.mapArea.push({ name: "中国", codeData: china, data: dataArray, geoCoordMap: mapInfoArray, index: 1 });
        this.loadMap(china, 'china', dataArray, mapInfoArray);
      }

      this.chart.hideLoading();
    },
    // 根据名称筛选出下级地区列表和客户信息
    getLayerData(layer, filterName, mapData) {
      if (layer == 0) {
        var qyLength = 0;
        var qyNames = [];
        // 找出中国的数据
        this.defaultData.forEach(e => {
          if (e.address.indexOf("中国") > -1) {
            qyLength++;
            qyNames.push(e.name)
          }
        })
        return [{ name: "中国", value: qyLength, qiyeData: qyNames, code: mapData["中国"][0] }]
      }

      if (layer > 0) {
        var dataArray = [];
        var areaArray = [];
        this.defaultData.forEach(e => {
          if (e.address.indexOf(filterName) > -1) {
            var addArr = e.address.split('-');
            if (addArr[layer]) {
              // console.log(addArr[layer]);
              var name = addArr[layer];
              var nameIndex = areaArray.indexOf(name);
              // 已经有相同名称
              if (nameIndex > -1) {
                dataArray[nameIndex].value++;
                dataArray[nameIndex].qiyeData.push(e.name);
              } else {
                dataArray.push({ name: addArr[layer], value: 1, qiyeData: [e.name], code: mapData[name][0] });
                areaArray.push(name)
              }
            }
          }
        })
        return dataArray;
      }
    },
    showIcons(index) {
      if (index == this.mapArea.length - 1) {
        return false;
      }
      return true;
    },
    // 顶部层级切换
    tabMap(map, index) {
      this.loadMap(map.codeData, map.name, map.data, map.geoCoordMap);
      this.maptype = map.index;
      this.mapArea.splice(index + 1);
    },
    // jsonCode-地图json
    // name-显示的区域名称
    // data-包含的区域名称和值
    // geoCoordMap-企业位置散点图
    loadMap(jsonCode, name, data, geoCoordMap) {
      // 根据名称找出省份或城市对应坐标(散点图用)
      var convertData = function (data) {
        var res = [];

        for (var i = 0; i < data.length; i++) {
          var geoCoord = geoCoordMap[data[i].name];

          if (geoCoord) {
            res.push({
              name: data[i].name,
              value: geoCoord[1].concat(data[i].value),
              data: data[i].qiyeData,
              code: geoCoord[0]
            });
          }
        }
        console.log(res)
        return res;
      };

      this.chart.clear();
      // 英文格式化中文
      var nameMap = { China: "中国" }
      echarts.registerMap(name, jsonCode);
      var option = {
        nameMap: nameMap,
        visualMap: {
          min: 0,
          max: 10,
          show: false,
          calculable: true,
          seriesIndex: [1],
          inRange: {
            color: ['#3aa3e5', '#0e5db5']
          },
        },
        geo: {
          map: name,
          zoom: 1,
          roam: true,
          itemStyle: {
            normal: {
              label: { show: true },
              color: '#F4F4F4',
              borderWidth: 1, //区域边框宽度
              borderColor: '#afafaf', //区域边框颜色
              areaColor: '#a3a3a3', //区域颜色
            },
            emphasis: {
              label: {
                show: true,
                color: "#fff"
              },
              borderColor: '#737575',
              areaColor: '#efefef',
            },
          },
        },
        series: [
          {
            name: 'eff',
            type: 'effectScatter',
            coordinateSystem: 'geo',
            symbolSize: 16,
            data: convertData(data),
            label: {
              show: true,
              offset: [0, 0], //偏移设置
              fontSize: 14,
              formatter(value) {
                // console.log(value);
                return value.data.value[2];
              },
              color: '#666666',
            },
            itemStyle: {
              shadowBlur: 10,
              normal: {
                color: '#36e3ff', //标志颜色
              },
            },
          },
          {
            name: 'MAP',
            type: 'map',
            geoIndex: 0,
            mapType: name,
            zoom: 1,

            data: data,
          },
        ]
      };
      this.chart.setOption(option);
    },
    // 跳转到url
    gotBoard(item) {
      if (!this.isEdit && item.url) {
        window.open(item.url)
      }
    }
  },
}
</script>

<style>
.toparea {
  position: absolute;
  top: 10px;
  left: 10;
  z-index: 9;
}

.toparea .mapitem {
  display: inline;
}

.toparea .mapitem i {
  margin: 0 8px;
}

.toparea .mapitem span {
  cursor: pointer;
}

.box {
  width: 1500px;
  height: 800px;
  border: solid 1px #333;
  float: left;
}

/* 弹窗样式 */
.echart-card {
  position: absolute;
  width: 230px;
  height: 240px;
  background-color: #f2f2f2;
  padding: 10px;
  color: #333;
  overflow-x: hidden;
  overflow-y: auto;
  display: none;
}

.set {
  margin-top: 8px;
  overflow-x: hidden;
  overflow-y: auto;
}

.flex {
  display: flex;
  align-items: center;
}

.qiyename {
  margin-left: 20px;
  width: 150px;
  text-align: left;
  overflow: hidden;
}
</style>